﻿using System;
using System.Collections.Generic;
using System.Text;
using TVOnline.Entities;
using EricUtility.Networking.Gathering;
using EricUtility;

namespace WatchSeriesHelper.Entities
{
    public abstract class AbstractSerieList : AbstractLoadingTuple
    {
        protected abstract string BaseURL { get; }

        protected readonly string m_Name;
        protected readonly List<TVShowInfo> m_Series = new List<TVShowInfo>();

        public string Name { get { return m_Name; } }
        public TVShowInfo[] Series { get { return m_Series.ToArray(); } }

        public AbstractSerieList(string name)
        {
            m_Name = name;
        }
        protected void AddShow(TVShowInfo s)
        {
            if( !m_Series.Contains(s) )
                m_Series.Add(s);
        }
        protected override void OnLoad()
        {
            m_Series.Clear();
            string src = EricUtility.Networking.Gathering.GatheringUtility.GetPageSource(BaseURL + m_Name);
            //src = src.Substring(src.IndexOf("<h2 class=\"listbig\">"));
            string showIdDeb = "<a href=\"http://watchseries.eu/serie/";
            string guillFin = "\"";
            string showNameDeb = " title=\"";
            int posShowDeb = 0;
            while ((posShowDeb = src.IndexOf(showIdDeb)) >= 0)
            {
                src = src.Substring(posShowDeb + showIdDeb.Length);
                int adrFin = src.IndexOf("</a>");
                int posShowIdFin = src.IndexOf(guillFin);
                string id = src.Substring(0, posShowIdFin);

                int posShowNameDeb = src.IndexOf(showNameDeb, posShowIdFin) + showNameDeb.Length;
                if (posShowNameDeb >= 0 && posShowNameDeb < adrFin)
                {
                    int posShowNameFin = src.IndexOf(guillFin, posShowNameDeb);
                    string name = src.Substring(posShowNameDeb, posShowNameFin - posShowNameDeb).Replace("watch serie ", "");

                    AddShow(new TVShowInfo(id, name));
                }
            }
        }
    }
}
